﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using GeneralLibs;
using Lists;

namespace ReportGenerators.BanHang.ThongKeBanHangLe
{
    public partial class FrmThongKeBanLeTongHop : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeBanLeTongHop()
        {
            InitializeComponent();
        }

        Store _Store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);

        private void FrmThongKeBanLeTongHop_Load(object sender, EventArgs e)
        {
            try
            {
                if (DesignMode) return;

                cmbKyBaoCao.SelectedIndex = 17;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void UpdateThue()
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("DECLARE @ID Uniqueidentifier \n" +
                                                "DECLARE  CursorVatTuHangHoa CURSOR FOR \n" +
                                                "	SELECT DISTINCT E.ID    \n" +
                                                "	FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n" +
                                                "		INNER JOIN LoaiChungTu C ON A.LoaiChungTuID = C.ID AND C.Ma IN ('HoaDonBanHang', 'HoaDonBanLe') \n" +
                                                "		INNER JOIN KhoanMucChungTu D ON B.ChungTuID = D.ChungTuID \n" +
                                                "		INNER JOIN VatTuHangHoa E ON E.ID = D.VatTuHangHoa1ID \n" +
                                                "	WHERE (D.Value7 - D.Value5)<=0 AND A.Ngay > @ThoiDiem \n" +
                                                "		AND E.ID IN \n" +
                                                "		( \n" +
                                                "			SELECT DISTINCT E.ID \n" +
                                                "			FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n" +
                                                "				INNER JOIN LoaiChungTu C ON A.LoaiChungTuID = C.ID AND C.Ma = 'HoaDonMuaHang' \n" +
                                                "				INNER JOIN KhoanMucChungTu D ON B.ChungTuID = D.ChungTuID \n" +
                                                "				INNER JOIN VatTuHangHoa E ON E.ID = D.VatTuHangHoa1ID \n" +
                                                "				INNER JOIN ThueSuat F ON F.ID = A.ThueSuat1ID \n" +
                                                "			WHERE F.MucThueSuat > 0 \n" +
                                                "		) \n" +
                                                "OPEN CursorVatTuHangHoa; \n" +
                                                "FETCH NEXT FROM CursorVatTuHangHoa INTO @ID	 \n" +
                                                "	 \n" +
                                                "WHILE @@FETCH_STATUS = 0 \n" +
                                                "BEGIN \n" +
                                                "	DECLARE @Thue money \n" +
                                                " \n" +
                                                "	SELECT TOP 1 @Thue = F.MucThueSuat \n" +
                                                "	FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n" +
                                                "		INNER JOIN LoaiChungTu C ON A.LoaiChungTuID = C.ID AND C.Ma = 'HoaDonMuaHang' \n" +
                                                "		INNER JOIN KhoanMucChungTu D ON B.ChungTuID = D.ChungTuID \n" +
                                                "		INNER JOIN VatTuHangHoa E ON E.ID = D.VatTuHangHoa1ID \n" +
                                                "		INNER JOIN ThueSuat F ON F.ID = A.ThueSuat1ID \n" +
                                                "		INNER JOIN Kho G ON B.Kho1ID = G.ID \n" +
                                                "	WHERE F.MucThueSuat > 0 AND E.ID = @ID \n" +
                                                "	 \n" +
                                                "	UPDATE KhoanMucChungTu SET Value4 = Value6 / (1 + @Thue), Value5 = Value1 * Value4 \n" +
                                                "	WHERE VatTuHangHoa1ID = @ID AND KhoanMucChungTuID IN \n" +
                                                "	( \n" +
                                                "		SELECT DISTINCT D.KhoanMucChungTuID    \n" +
                                                "		FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n" +
                                                "			INNER JOIN LoaiChungTu C ON A.LoaiChungTuID = C.ID AND C.Ma IN ('HoaDonBanHang', 'HoaDonBanLe') \n" +
                                                "			INNER JOIN KhoanMucChungTu D ON B.ChungTuID = D.ChungTuID \n" +
                                                "		WHERE (D.Value7 - D.Value5)<=0 AND A.Ngay > @ThoiDiem \n" +
                                                "	) \n" +
                                                "		 \n" +
                                                "	FETCH NEXT FROM CursorVatTuHangHoa INTO @ID	 \n" +
                                                "END \n" +
                                                "CLOSE CursorVatTuHangHoa; \n" +
                                                "DEALLOCATE CursorVatTuHangHoa \n");
                cmd.CommandType = CommandType.Text;
                cmd.CommandTimeout = Config.TimeOut;
                cmd.Parameters.Clear();
                ThoiDiemKhoaSo thoiDiemKSGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(DateTime.Now);
                cmd.Parameters.AddWithValue("@ThoiDiem", thoiDiemKSGanNhat.ThoiDiem);

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                FrmProgressBar.FinishShowProgress();
                con.Close();
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            //TTSHN cần tính thuế lại cho chắc
            if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("TTSHN")
                   || DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("MINH"))
            {
                UpdateThue();
            }

            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            DsThongKeBanLe ds = new DsThongKeBanLe();
            BasicForms.FrmProgressBar.StartShowProgress("Đang xử lý");

            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand(); cmd.CommandTimeout = Config.TimeOut;
                cmd.CommandTimeout = 1000 * 10;

                ds.DetailTongHop.Clear();
                //cmd.CommandText = "Select_Detail_KhoanMucThongKeBanLe";
                cmd.CommandText = string.Format("SELECT TBL1.UserName, TBL1.FullName, TBL2.UserName UserName2, TBL2.FullName FullName2, TongTienGiaLe, TongTienChietKhau, TongTienTraLai \n" +
                                                "FROM ( \n" +
                                                "SELECT E.UserName, E.FullName,  \n" +
                                                "		SUM(D.Value13) TongTienGiaLe, SUM(D.Value13-D.Value7) TongTienChietKhau  \n" +
                                                "FROM ChungTu A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID \n" +
                                                "	INNER JOIN LoaiChungTu C ON C.ID = A.LoaiChungTuID AND C.Ma = 'HoaDonBanLe' \n" +
                                                "	INNER JOIN KhoanMucChungTu D ON D.ChungTuID = B.ChungTuID \n" +
                                                "	INNER JOIN [User] E ON E.ID = A.UserID \n" +
                                                "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi AND A.GhiSo = 1 \n" +
                                                "			AND D.Value5 IS NOT NULL AND D.Value3 IS NOT NULL   \n" +
                                                "GROUP BY A.UserID, E.UserName, E.FullName \n" +
                                                ") AS TBL1 FULL JOIN ( \n" +
                                                "SELECT E.UserName, E.FullName, SUM(A.SoTienNT) TongTienTraLai \n" +
                                                "FROM ChungTu A INNER JOIN LoaiChungTu C ON C.ID = A.LoaiChungTuID AND C.Ma IN ('HangBanTraLai') AND A.DienGiai = N'Khách lẻ trả lại hàng' \n" +
                                                "	INNER JOIN [User] E ON E.ID = A.UserID \n" +
                                                "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi AND A.GhiSo = 1 \n" +
                                                "--			AND D.Value5 IS NOT NULL AND D.Value3 IS NOT NULL  \n" +
                                                "GROUP BY A.UserID, E.UserName, E.FullName \n" +
                                                ") AS TBL2 ON TBL1.UserName = TBL2.UserName \n");

                cmd.CommandType = CommandType.Text;

                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds.DetailTongHop);

                foreach (DataRow row in ds.DetailTongHop.Rows)
                {
                    //Trường hợp chỉ có trả lại thì UserName IS NULL nhưng UserName2 lại có giá trị
                    if (!(row["UserName"] is string) || row["UserName"].ToString() == "") row["UserName"] = row["UserName2"].ToString();
                    if (!(row["FullName"] is string) || row["FullName"].ToString() == "") row["FullName"] = row["FullName2"].ToString();
                    decimal tongTienGiaLe = CommonLib.ConvertToDecimal(row["TongTienGiaLe"]);
                    decimal tongTienChietKhau = CommonLib.ConvertToDecimal(row["TongTienChietKhau"]);
                    decimal tongTienTraLai = CommonLib.ConvertToDecimal(row["TongTienTraLai"]);

                    decimal tongTienThanhToan = tongTienGiaLe - tongTienChietKhau - tongTienTraLai;

                    row["TongTienThanhToan"] = tongTienThanhToan;
                }

                gridControlThongKeBanLe.DataSource = ds.DetailTongHop;
                FormatNumberInGridViewLamTron(gridViewThongKeBanLe);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                if (con.State == ConnectionState.Open) con.Close();
                //con = null;
                BasicForms.FrmProgressBar.FinishShowProgress();
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (!_Store.Ten.ToUpper().Contains("TTSHN"))
                gridControlThongKeBanLe.ShowPrintPreview();
        }
    }
}
